package com.wenmingliang.blog.advice;

import com.wenmingliang.blog.vo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@ControllerAdvice(annotations = Controller.class)
public class ExceptionAdvice {

    private static Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result handException(Exception e, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
        logger.error("服务器异常！");
        for (StackTraceElement errMessage : e.getStackTrace()) {
            logger.error(errMessage.toString());
        }

//        String xRequestedWith = httpServletRequest.getHeader("x-requested-with");

        // 判断是否是异步处理请求,如果是异步请求,则返回json数据，否则返回页面(前后端分离没必要这样搞)
//        if ("XMLHttpRequest".equals(xRequestedWith)){
//            return Result.fail(-200, "这是异步请求异常");
//        } else {
//            return Result.fail(-200, "系统异常");
//        }

        return Result.fail(-200, "系统异常");
    }
}
